import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import loadingUtil from "@/utils/loadingUtil";
import store from '@/store'
import {getToken} from '@/utils/auth'
const qs = require("qs")
console.log(store)

const ERROR_CODE={
    9001:"系统未知异常，请联系系统管理人员！",
    5001:"业务自定义异常",
}


const baseUrl = process.env.VUE_APP_BASE_API
function formData(obj){
    if (obj instanceof Object){
        let formData = new FormData()
        Object.keys(obj).forEach(key=>{
            formData.append(key,obj[key])
        })
        return formData
    }
    return obj
}
// create an axios instance
const service = axios.create({
    baseURL: baseUrl, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 10000, // request timeout
    transformRequest: data => {
        // console.log(formData(data))
        // return qs.stringify(data)
        return formData(data)
    }
})
// request interceptor
service.interceptors.request.use(
    config => {
        loadingUtil.loading()
        if ('/vue-element-admin/user/info' === config.url) {
            config.baseURL = '/'
        }
        if (store.getters.token) {
            // let each request carry token
            // ['X-Token'] is a custom headers key
            // please modify it according to the actual situation
            config.headers['X-Token'] = getToken()
        }
        return config
    },
    error => {
        // do something with request error
        // console.log(error) // for debug
        store.dispatch('app/setSpinner',-1)
        return Promise.reject(error)
    }
)
// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        loadingUtil.close()
        const res = response.data
        if (res.code == 200) return res

        else if (5001 == res.code){
            Message({
                message: res.message || "未知异常代码",
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject(new Error(res.message || 'Error'))
        }
        else{
            Message({
                message: ERROR_CODE[res.code] || "未知异常代码",
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject(new Error(res.message || 'Error'))
        }
    },
    error => {
        loadingUtil.close()
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
